package com.riguz.forks.framework.route.impl;

import java.util.List;

import com.riguz.forks.framework.mvc.RequestHandler;

class RouteTree extends RadixTree<RequestHandler>{
    public RequestHandler find(String path, List<String> args) {
        RequestHandler v = find(this.rootNode, path, args);
        System.out.println("find:" + path + " =>" + v);
        return v;
    }

    private RequestHandler find(TreeNode<RequestHandler> parent, String path, List<String> args) {
        //System.out.println("->" + path + " in " + parent.path);
        
        for (int i = 0; i < parent.path.length(); i++) {
            if(path.length() < parent.path.length())
                return null;
            char p = parent.path.charAt(i);
            if(p == '*'){
                String arg = path.substring(i);
                args.add(arg);
                System.out.println("*arg=" + arg);
                return parent.value;
            }
            if(p == '?'){
                int j = i;
                for(; j < path.length(); j++){
                    if(path.charAt(j) == '/')
                        break;
                }
                String arg = path.substring(i, j);
                args.add(arg);
                System.out.println("?arg=" + arg);
                path = path.substring(0, i) + "?" + path.substring(j);
                continue;
            }
            if(path.charAt(i) != p)
                return null;
        }
        if(path.length() == parent.path.length())
            return parent.value;
        // trying to find in children
        String subpath = path.substring(parent.path.length());
        for(TreeNode<RequestHandler> child:parent.children){
            char p = child.path.charAt(0);
            if(p == subpath.charAt(0) || p == '*' || p == '?')
                return find(child, subpath, args);
        }
        return null;
    }
}
